import React, {ChangeEvent, useEffect, useState} from 'react'
import {Button, Input, message, Radio, Space} from 'antd'
import {TextWidget, useDesigner} from '@designable/react'
import {GlobalRegistry} from '@designable/core'
import {observer} from '@formily/react'
import {getSchema, schema2Table, setSchema} from '../service'
import {createForm, createTable, getFormById, updateForm, updateTable} from "../service/api";

/***
 * 获取地址栏后面参数
 * @param name 返回具体哪个字段
 */
export const getParams = (name?: string) => {
    var params: any = {};
    if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
        var paramArray = decodeURIComponent(window.location.search).substring(1, window.location.search.length).split("&");
        if (paramArray.length > 0) {
            paramArray.forEach(function (currentValue) {
                params[currentValue.split("=")[0]] = currentValue.split("=")[1];
            });
        }
    }
    if (name) return params[name];
    return params;
}

export const ActionsWidget = observer(() => {
    const designer = useDesigner()
    const [table, setTable] = useState(null)
    const [tableAlias, setTableAlias] = useState('');
    const [refreshLang, setRefreshLang] = useState<number>(-1);

    const tableAliasPlaceholderMemo = React.useMemo(() => {
        const placeholder = {
            'zh-cn': '请输入表别名',
            'en-us': 'please enter table alias'
        }
        const lang = GlobalRegistry.getDesignerLanguage() || 'zh-cn'
        return placeholder[lang as keyof typeof placeholder]
    }, [refreshLang]);

    const setEditStatus = (id: string) => {
        window.history.pushState('', '', "?form=" + id)
    }

    // 发布
    const publish = async () => {
        const schema = getSchema(designer)
        if (!schema) return
        const defaultTable = schema2Table(schema)
        const formId = getParams('form')
        const isEdit = Boolean(formId)
        const tableName = isEdit && table ? table : (schema.schema as any)['x-designable-source-name']
        const formData = isEdit ? await update(defaultTable, tableName, schema, formId) : await create(defaultTable, tableName, schema)
        if (!formData) return

        setEditStatus(formData?.data?._id || formId)
        message.success(`${isEdit ? '编辑' : '新增'}成功`);
    }

    //新增
    const create = async (defaultTable: any, tableName: string, schema: any) => {
        await createTable(defaultTable, tableName)
        const formData = await createForm(schema, tableName, tableAlias)
        if (!formData) return
        return formData
    }

    //编辑
    const update = async (defaultTable: any, tableName: string, schema: any, formId: string) => {
        await updateTable(defaultTable, tableName)
        const formData = await updateForm(formId, schema, tableName, tableAlias)
        if (!formData) return
        return formData
    }

    const changeTableAlias = (e: ChangeEvent) => {
        setTableAlias((e.target as any).value)
    }

    useEffect(() => {
        (async () => {
            setTimeout(async () => {
                const formId = getParams('form')
                if (!formId) return
                const formData = await getFormById(formId)
                const {json, tableName, tableAlias=''} = formData?.data || {}
                setSchema(designer, json)
                setTable(tableName)
                setTableAlias(tableAlias)
            }, 0)
        })()
    }, [])


    return (
        <Space style={{marginRight: 10}}>
            <Input placeholder={tableAliasPlaceholderMemo} name="inputs" allowClear onChange={changeTableAlias}
                   value={tableAlias}/>
            <Radio.Group
                value={GlobalRegistry.getDesignerLanguage()}
                optionType="button"
                options={[
                    {label: 'English', value: 'en-us'},
                    {label: '简体中文', value: 'zh-cn'},
                ]}
                onChange={(e) => {
                    GlobalRegistry.setDesignerLanguage(e.target.value)
                    setRefreshLang(Math.random())
                }}
            />
            <Button
                type="primary"
                onClick={() => {
                    publish()
                }}
            >
                <TextWidget>Publish</TextWidget>
            </Button>
        </Space>
    )
})
